package com.alipay.sofa.award.biz.service.model;

import java.util.concurrent.TimeUnit;

/**
 * QpsControlModel
 *
 * @author yangguanchao
 * @since 2018/09/08
 */
public class QpsControlModel {

    /***
     * qps 1000
     */
    private long qpsLimitCount    = 1000L;

    /***
     * period ms
     */
    private long qpsPeriodMillis  = 1000L;

    /**
     * latest current time
     */
    private long latestTimeMillis = 0L;

    /**
     * Counter
     */
    private long counter          = 0L;

    public QpsControlModel(long qpsLimitCount, long qpsPeriod, TimeUnit timeUnit) {
        this.qpsLimitCount = qpsLimitCount;
        this.qpsPeriodMillis = timeUnit.toMillis(qpsPeriod);
        this.latestTimeMillis = System.currentTimeMillis();
    }

    public boolean canPass() {
        synchronized (this) {
            if (++this.counter > this.qpsLimitCount) {
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis <= this.latestTimeMillis + this.qpsPeriodMillis) {
                    //limited
                    return false;
                } else {
                    this.counter = 1L;
                    this.latestTimeMillis = currentTimeMillis;
                    return true;
                }
            } else {
                return true;
            }
        }
    }
}
